# User authentication related functions
import hashlib
from app.utils.database import get_db_cursor

def hash_password(password):
    """Password hashing"""
    return hashlib.sha256(password.encode()).hexdigest()

def check_password(password, hashed):
    """Verify password"""
    return hash_password(password) == hashed

def get_user_by_username(username):
    """Get user by username"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
        user = cursor.fetchone()
        return dict(user) if user else None
    finally:
        cursor.close()
        conn.close()

def get_user_by_id(user_id):
    """Get user by ID"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("SELECT * FROM users WHERE user_id = %s", (user_id,))
        user = cursor.fetchone()
        return dict(user) if user else None
    finally:
        cursor.close()
        conn.close()

def create_user(username, email, age, gender, balance, password):
    """Create user"""
    conn, cursor = get_db_cursor()
    try:
        hashed_password = hash_password(password)
        cursor.execute("""
            INSERT INTO users (username, email, age, gender, balance, password_hash)
            VALUES (%s, %s, %s, %s, %s, %s)
            RETURNING user_id
        """, (username, email, age, gender, balance, hashed_password))
        user_id = cursor.fetchone()['user_id']
        conn.commit()
        return user_id
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()

def update_user_balance(user_id, amount):
    """Update user balance"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("""
            UPDATE users SET balance = balance + %s WHERE user_id = %s
            RETURNING balance
        """, (amount, user_id))
        result = cursor.fetchone()
        conn.commit()
        return float(result['balance']) if result else None
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()

def deduct_user_balance(user_id, amount):
    """Deduct user balance"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("""
            UPDATE users SET balance = balance - %s WHERE user_id = %s
            RETURNING balance
        """, (amount, user_id))
        result = cursor.fetchone()
        conn.commit()
        return float(result['balance']) if result else None
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()
